package com.ncmmall.api.apis.mall.live;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.NumberUtil;
import com.ncmmall.api.apis.service.Result;
import com.ncmmall.api.security.Securitys;
import com.feijin.commons.lang.Requires;
import com.ncmmall.domain.business.live.LiveBalanceRecord;
import com.ncmmall.domain.security.user.WebUser;
import com.ncmmall.querychannel.service.QueryChannelService;
import com.google.common.collect.ImmutableMap;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 主播钱包相关接口
 *
 * @author likaikai
 * @date 2021-2-2 16:36:35
 */
@RestController
@RequestMapping("/live/wallet")
@Slf4j
public class LiveWalletApi {

    @Autowired
    private QueryChannelService queryChannelService;

    /**
     * 主播钱包首页
     */
    @GetMapping
    public Result home(HttpServletRequest request) {
        Result result = new Result();
        try {
            WebUser user = Securitys.user(request);
            Requires.isTrue(user.getLiveType() == 1, "当前用户不是主播");
            Map<String, Object> map = new HashMap<>();

            double balance = user.getLiveBalance();

            //已提现
            double withdraw = queryChannelService.selectSum("select IFNULL(sum(money), 0) from live_money_record where anchor_id = :aid and type = 2",
                    ImmutableMap.of("aid", user.getId()));

            //待成交
            double frozen = queryChannelService.selectSum("select IFNULL(sum(money), 0) from live_money_record where anchor_id = :aid and type = 3",
                    ImmutableMap.of("aid", user.getId()));

            //佣金输入
            double total = queryChannelService.selectSum("select IFNULL(sum(money), 0) from live_money_record where anchor_id = :aid and type = 1",
                    ImmutableMap.of("aid", user.getId()));

            // 累计总佣金
            map.put("total", NumberUtil.roundDown(total + frozen, 2));
            //已提现佣金
            map.put("withdraw", NumberUtil.roundDown(withdraw, 2));
            //可提现佣金
            map.put("balance", NumberUtil.roundDown(balance, 2));
            //待成交
            map.put("frozen", NumberUtil.roundDown(frozen, 2));

            //todo 直播数据统计

            return result.ok().inject(map);
        } catch (IllegalArgumentException e) {
            return result.fail().setMsg(e.getMessage());
        } catch (Exception e) {
            log.error("获取钱包数据异常", e);
            return result.fail().setMsg("获取数据异常");
        }
    }

    /**
     * 主播钱包明细
     *
     * @param type 1、佣金收入 2、佣金提现 3、待成交
     */
    @GetMapping("/detailed")
    public Result detailed(HttpServletRequest request, @RequestParam(defaultValue = "0") Integer type) {
        Result result = new Result();
        try {
            WebUser user = Securitys.user(request);
            Requires.isTrue(user.getLiveType() == 1, "当前用户不是主播");
            Map<String, Object> map = new HashMap<>();

            double balance = user.getLiveBalance();

            //已提现
            double withdraw = queryChannelService.selectSum("select IFNULL(sum(money), 0) from live_money_record where anchor_id = :aid and type = 2",
                    ImmutableMap.of("aid", user.getId()));

            //待成交
            double frozen = queryChannelService.selectSum("select IFNULL(sum(money), 0) from live_money_record where anchor_id = :aid and type = 3",
                    ImmutableMap.of("aid", user.getId()));

            //佣金输入
            double total = queryChannelService.selectSum("select IFNULL(sum(money), 0) from live_money_record where anchor_id = :aid and type = 1",
                    ImmutableMap.of("aid", user.getId()));

            // 累计总佣金
            map.put("total", NumberUtil.roundDown(total + frozen, 2));
            //已提现佣金
            map.put("withdraw", NumberUtil.roundDown(withdraw, 2));
            //可提现佣金
            map.put("balance", NumberUtil.roundDown(balance, 2));
            //待成交
            map.put("frozen", NumberUtil.roundDown(frozen, 2));

            String hql = "select r from LiveBalanceRecord r where r.anchor.id = :id";
            Map<String, Object> params = new HashMap<>();
            params.put("id", user.getId());

            if (type > 0) {
                hql += " and r.type = :type";
                params.put("type", type);
            }

            hql += " and r.createTime > :date order by r.id desc";
            params.put("date", DateUtil.offsetMonth(new Date(), -3).toTimestamp());

            List<LiveBalanceRecord> list = queryChannelService.findAll(hql, params, LiveBalanceRecord.class);
            map.put("list", list);

            return result.ok().inject(map);

        } catch (IllegalArgumentException e) {
            return result.fail().setMsg(e.getMessage());
        } catch (Exception e) {
            log.error("获取钱包详情异常", e);
            return result.fail().setMsg("获取数据异常");
        }
    }

}
